package com.customer.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.customer.mall.domain.vo.CategoryVO;
import com.customer.mall.mapper.CategoryMapper;
import com.customer.mall.domain.Category;
import com.customer.mall.service.ICategoryService;
import com.customer.mall.util.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author BaiGGG
 * @since 2023-06-25
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public ResponseResult<Page<Category>> pageCategory(Integer pageNum, Integer pageSize) {
        Page<Category> categoryPage = new Page<>(pageNum, pageSize);
        Page<CategoryVO> categoryVoPage = new Page<>();
        categoryVoPage.setRecords(page(categoryPage).getRecords().stream().map(item ->
            new CategoryVO(item.getId(), item.getCode(), item.getName(), item.getCreateTime(), item.getUpdateTime())
        ).collect(Collectors.toList()));
        BeanUtils.copyProperties(categoryPage, categoryVoPage, "records");
        return ResponseResult.okResult(categoryVoPage);
    }

    @Override
    public ResponseResult<CategoryVO> getCategoryById(Integer id) {
        Category category = getById(id);
        if(Objects.isNull(category)){
            return ResponseResult.failResult();
        }
        CategoryVO categoryVo = new CategoryVO();
        BeanUtils.copyProperties(category, categoryVo);
        return ResponseResult.okResult(categoryVo);
    }

    @Override
    public ResponseResult<String> insertCategory(Category category) {
        String code = category.getCode();
        Category getCategory = getOne(new QueryWrapper<Category>().eq("code", code));
        if(!Objects.isNull(getCategory)){
            return ResponseResult.failResult("已经存在这个代码的衣服");
        }
        if(!save(category)){
            return ResponseResult.failResult("保存失败");
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<String> updateCategory(Category category) {
        if(!updateById(category)){
            return ResponseResult.failResult("修改失败");
        }
        return ResponseResult.okResult();
    }

}
